<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.courseName" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入课程名称查询"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button  type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table stripe :data="data.tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="img" label="课程封面">
          <template v-slot="scope">
            <el-image style="width: 60px; height: 40px; border-radius: 5px; display: block" v-if="scope.row.img"
                      :src="scope.row.img" :preview-src-list="[scope.row.img]" preview-teleported></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="courseName" label="课程名称" />
        <el-table-column prop="teacherName" label="授课教师" />
        <el-table-column prop="score" label="课程学分" />
        <el-table-column label="操作" width="100" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" circle :icon="Edit" @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" circle :icon="Delete" @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination @current-change="load" background layout="prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total" />
    </div>

    <el-dialog title="课程信息" v-model="data.formVisible" width="40%" destroy-on-close>
      <el-form ref="form" :model="data.form" label-width="70px" style="padding: 20px">
        <el-form-item prop="img" label="课程封面">
          <el-form-item prop="img" label="课程封面">
            <el-upload
                :action="baseUrl + '/files/upload'"
                :on-success="handleFileUpload"
                list-type="picture"
            >
              <el-button type="primary">上传封面</el-button>
            </el-upload>
          </el-form-item>
        </el-form-item>

        <el-form-item prop="courseName" label="课程名称">
          <el-input v-model="data.form.courseName" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        <el-form-item prop="score" label="课程学分">
          <el-input v-model="data.form.score" placeholder="请输入课程学分"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.min.css'; // 引入样式
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/utils/request.js';
import { Delete, Edit } from '@element-plus/icons-vue';

const baseUrl = import.meta.env.VITE_BASE_URL;

const data = reactive({
  user: JSON.parse(localStorage.getItem('user') || '{}'),
  formVisible: false,
  form: {
    img: ''  // 用于存储裁剪后的图片URL
  },
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  courseName: null,
  ids: [],
  uploadParams: {
    bucket: 'green', // Bucket name is fixed
    objectName: 'CourseCoverImage', // Object name is fixed
  },
});

const cropperInstance = ref(null);
const imageRef = ref(null);
const imagePreviewRef = ref(null); // 用于显示裁剪后的图片

const load = () => {
  request.get('/course/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      courseName: data.courseName
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list || [];
      data.total = res.data?.total;
    } else {
      ElMessage.error(res.msg);
    }
  });
};
const handleFileUpload = (res) => {
  data.form.img = res.data;
};
const handleAdd = () => {
  data.form = {};
  data.formVisible = true;
};

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.formVisible = true;
};

const add = () => {
  request.post('/course/add', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const update = () => {
  request.put('/course/update', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      data.formVisible = false;
      load();
    }
  });
};

const save = () => {
  data.form.id ? update() : add();
};

const del = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning' }).then(res => {
    request.delete('/course/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功');
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => {
    console.error(err);
  });
};

const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning('请选择数据');
    return;
  }
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning' }).then(res => {
    request.delete('/course/delete/batch', { data: data.ids }).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功');
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => {
    console.error(err);
  });
};

const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.id);
};

const reset = () => {
  data.courseName = null;
  load();
};

const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    data.form.originalFileName = file.name; // 保存原始文件名
    // 创建 FileReader 对象并读取文件
    const reader = new FileReader();
    reader.onload = (e) => {
      // 将文件加载到裁剪区域
      const imageUrl = e.target.result;
      if (cropperInstance.value) {
        cropperInstance.value.destroy(); // 销毁已有的实例
      }
      imageRef.value.src = imageUrl; // 设置图片
      imageRef.value.onload = () => {
        // 确保图片加载完成后初始化 cropper
        cropperInstance.value = new Cropper(imageRef.value, {
          aspectRatio: 1, // 设置裁剪框为正方形
          viewMode: 1, // 设置为可视模式
          cropBoxResizable: false, // 禁止调整裁剪框大小
          cropBoxMovable: false, // 禁止移动裁剪框
          movable: true, // 允许移动图片
          resizable: false, // 禁止调整裁剪框大小
          zoomable: true, // 允许放大和缩小图片
          scalable: true, // 允许放大和缩小图片
          dragMode: 'move', // 允许通过拖动图片来调整位置
          ready() {
            // 初始化时设置裁剪区域的大小和位置
            const canvas = cropperInstance.value.getCropBoxData();
            cropperInstance.value.setCropBoxData({
              width: 200, // 设置裁剪框的宽度
              height: 200, // 设置裁剪框的高度
              left: canvas.left, // 裁剪框的左上角 X 坐标
              top: canvas.top, // 裁剪框的左上角 Y 坐标
            });
          },
          crop(event) {
            // 每次裁剪时更新预览
            const canvas = cropperInstance.value.getCroppedCanvas();
            if (imagePreviewRef.value) {
              imagePreviewRef.value.src = canvas.toDataURL();
            }
          },
        });
      };
    };
    reader.readAsDataURL(file);
  }
};
const handleUpload = () => {
  // 检查是否已经进行了裁剪操作
  if (!cropperInstance.value) {
    ElMessage.error('请先选择并裁剪图片');
    return;
  }

  // 获取裁剪后的图片的 Canvas 对象
  const canvas = cropperInstance.value.getCroppedCanvas();
  if (!canvas) {
    ElMessage.error('裁剪图片失败，请重新裁剪');
    return;
  }

  // 将 Canvas 转换为 Blob 对象（二进制文件）
  canvas.toBlob((blob) => {
    if (!blob) {
      ElMessage.error('裁剪图片转换失败，请重试');
      return;
    }

    // 创建 FormData 对象用于上传
    const formData = new FormData();
    // 获取原始文件的名称
    const originalFileName = data.form.originalFileName || 'cropped-image.jpg'; // 如果没有原始文件名，则使用默认值
    formData.append('uploadFile', blob, originalFileName);
    // formData.append('uploadFile', blob, 'cropped-image.jpg'); // 文件名自定义
    formData.append('bucket', data.uploadParams.bucket); // 存储桶名称
    formData.append('objectName', data.uploadParams.objectName); // 对象名称

    // 打印 FormData 的内容，确认数据是否正确添加
    for (let [key, value] of formData.entries()) {
      console.log(`${key}: ${value}`);
    }

    // 发起上传请求
    request.post(`${baseUrl}/oss/upload`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }, // 设置请求头
      transformRequest: [(data, headers) => {
        // 确保 FormData 的内容正确传递
        return data;
      }]
    })
        .then((response) => {
          if (response.code === '200') {
            // 保存返回的图片 URL 到表单数据中
            data.form.img = response.data; // 根据后端返回的数据结构调整
            ElMessage.success('图片上传成功');
          } else {
            ElMessage.error(response.msg || '上传失败，请重试');
          }
        })
        .catch((error) => {
          ElMessage.error('上传失败，请检查网络或联系管理员');
          console.error('Upload error:', error);
        });
  }, 'image/jpeg'); // 指定图片格式为 JPEG
};
load();
</script>
